package com.mojo.webflux.service.impl;

import com.mojo.webflux.pojo.User;
import com.mojo.webflux.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Map<Integer, User> userMap = new HashMap();

    static {
        userMap.put(1, new User(1, "mojo", 1));
        userMap.put(2, new User(2, "xishi", 2));
        userMap.put(3, new User(3, "beishang", 3));
    }

    @Override
    public Mono<User> findById(Integer id) {
        return Mono.justOrEmpty(userMap.get(id));
    }

    @Override
    public Flux<User> findAll() {
        return Flux.fromIterable(userMap.values());
    }

    @Override
    public Mono<Void> add(Mono<User> userMono) {
        return userMono.doOnNext(user -> {
            Integer id = user.getId() + 1;
            userMap.put(id, user);
            //终止信号
            System.out.println(userMap);
        }).then(Mono.empty());
    }

}
